package com.simple.chiraliumauth.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.simple.chiralium.common.core.util.Result;
import com.simple.chiralium.upms.api.dto.UserInfo;
import com.simple.chiralium.upms.api.entity.SysUser;
import com.simple.chiralium.upms.api.feign.RemoteUserService;
import com.simple.chiraliumauth.dto.ChiraliumUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * User Service 实现类
 *
 * @author SimpleZzz
 * @date 2021/11/29
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserDetailsService {

    private final RemoteUserService remoteUserService;

    /**
     * 根据用户名获取用户信息
     *
     * @param username 用户名
     * @return {@link UserDetails}
     * @throws UsernameNotFoundException 用户名没有发现异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<UserInfo> result = remoteUserService.info(username);
        return getUserDetails(result);
    }

    /**
     * 获取用户详细信息
     *
     * @param result 结果
     * @return {@link UserDetails}
     */
    private UserDetails getUserDetails(Result<UserInfo> result) {
        if (result==null||result.getData()==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 用户信息
        UserInfo userInfo = result.getData();
        // 权限集合
        Set<String> authSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(userInfo.getRoleIds())) {
            Arrays.stream(userInfo.getRoleIds()).forEach(role -> authSet.add("role_" + role));
        }
        if (ArrayUtil.isNotEmpty(userInfo.getPermissions())) {
            authSet.addAll(Arrays.asList(userInfo.getPermissions()));
        }
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));

        SysUser sysUser = userInfo.getSysUser();
        return new ChiraliumUser(sysUser.getPkId(), sysUser.getUsername(), sysUser.getPassword(),
                StrUtil.equals(sysUser.getLockFlag(), "0"), true, true, true, authorities);
    }
}
